/*
 * 控制类权限资源管理
 */

RoleCurd = Ext.extend(RockyPanelCurd, {
	baseUrl : 'role.action',
	winCfg : {
		maximizable : true,
		width : 500,
		title : "角色详细信息"
	},
	title : "系统角色管理",
	layout : "border",
	closable : true,
	constructor : function(config) {
		this.tree = new Ext.tree.TreePanel({
			tbar : ['   ', {
				text : '新增',
				pressed : true,
				handler : this.create,
				scope : this
			}, '   ', {
				text : '修改',
				pressed : true,
				handler : this.edit,
				scope : this
			}, '   ', {
				text : '删除',
				pressed : true,
				handler : this.removeData,
				scope : this
			}, '   ', {
				text : '刷新',
				pressed : true,
				handler : this.refresh,
				scope : this
			}, new Ext.Toolbar.Fill(), '   '],
			region : 'west',
			title : '权限角色管理',
			split : true,
			width : 300,
			minSize : 175,
			maxSize : 400,
			collapsible : true,
			layout : 'accordion',
			layoutConfig : {
				animate : true
			},
			autoScroll : true,
			animate : true,
			border : false,
			rootVisible : false,
			root : new Ext.tree.AsyncTreeNode({
				id : "root",
				text : "系统角色",
				"isWebnewscat" : "false",
				loader : new RockyCurd.TreeLoader({
					dataUrl : "role.action?cmd=read",
					expanded : true,
					nodeMeta : {
						id : 'id',
						text : 'rolename'
					}
				})
			}),
			listeners : {
				'click' : this.onClick,
				scope : this
			}
		});
		this.tree.root.expand(true);
		this.controlResouceTree = new Ext.tree.TreePanel({
			title : '控制类',
			disabled : true,
			width : 300,
			buttonAlign : 'right',
			checkModel : 'cascade',
			onlyLeafCheckable : false,
			animate : false,
			rootVisible : true,
			autoScroll : true,
			lines : true,
			loader : new RockyCurd.TreeLoader({
				dataUrl : "genControlResourceTree.action",
				expanded : true,
				nodeMeta : {
					id : 'id',
					text : 'name'
				},
				baseAttrs : {
					uiProvider : Ext.ux.TreeCheckNodeUI
				}
			}),
			root : new Ext.tree.AsyncTreeNode({
				id : '-1',
				text : '根结点',
				uiProvider : Ext.ux.TreeCheckNodeUI
			}),
			listeners : {
				'show' : function() {
					this.root.expand(true);
				}
			},
			buttons : [{
				text : '控制类资源授权保存',
				handler : function() {
					var record = this.controlResouceTree.getChecked();
					if (record.length == 0) {
						Ext.MessageBox.alert('提示', "请选择资源再保存。");
						return false;
					}
					var ids = '';
					Ext.each(record, function(node, index) {
						if (node.id == "-1") {
							return;
						}
						if (index == record.length - 1) {
							ids += node.id;
						} else {
							ids += node.id + ",";
						}
					}, this);
					var role = this.tree.getSelectionModel().getSelectedNode();
					if (!role) {
						Ext.Msg.alert("提示", "请先选择左边的角色再进行授权!");
						return false;
					}
					var roleId = role.id;
					Ext.Ajax.request({
						url : 'permission.action?cmd=save',
						params : {
							'roleId' : roleId,
							'id' : ids,
							'from' : 'action'
						},
						method : 'POST',
						success : function(response) {
							Ext.getBody().unmask();
							var r = Ext.decode(response.responseText);
							if (!r.success) {
								Ext.Msg.alert("提示信息", "失败，由以下原因所致：<br/>" + (r.errors ? r.errors : "未知原因"));
							} else {
								Ext.Msg.alert("提示信息", "保存成功!");
							}
						},
						failure : function(Optional) {
							Ext.getBody().unmask();
							Ext.Msg.alert("提示信息", "连接服务器失败!");
						},
						scope : this
					});
				},
				scope : this
			}]
		});
		this.menuResourceTree = new Ext.tree.TreePanel({
			region : 'center',
			width : 300,
			title : '菜单类',
			buttonAlign : 'right',
			checkModel : 'cascade',
			onlyLeafCheckable : false,
			animate : false,
			rootVisible : true,
			autoScroll : true,
			lines : true,
			loader : new RockyCurd.TreeLoader({
				dataUrl : "genResourceTree.action?from=menu",
				expanded : true,
				nodeMeta : {
					id : 'id',
					text : 'name'
				},
				baseAttrs : {
					uiProvider : Ext.ux.TreeCheckNodeUI
				}
			}),
			root : new Ext.tree.AsyncTreeNode({
				id : '0',
				text : '根结点',
				uiProvider : Ext.ux.TreeCheckNodeUI
			}),
			listeners : {
				'show' : function() {
					this.menuResourceTree.root.expand(true, true, function() {
						try {
							this.tree.fireEvent('click', this.tree.getSelectionModel().getSelectedNode());
						} catch (e) {
						}
					}.createDelegate(this));
				},
				scope : this
			},
			buttons : [{
				text : '菜单类资源授权保存',
				handler : function() {
					var record = this.menuResourceTree.getChecked();
					if (record.length == 0) {
						Ext.MessageBox.alert('提示', "请选择资源再保存。");
						return false;
					}
					var ids = '';
					Ext.each(record, function(node, index) {
						if (node.id == "-1") {
							return;
						}
						if (index == record.length - 1) {
							ids += node.id;
						} else {
							ids += node.id + ",";
						}
					}, this);
					var role = this.tree.getSelectionModel().getSelectedNode();
					if (!role) {
						Ext.Msg.alert("提示", "请先选择左边的角色再进行授权!");
						return false;
					}
					var roleId = role.id;
					Ext.Ajax.request({
						url : 'addRoleResourceR.action',
						params : {
							'roleId' : roleId,
							'id' : ids,
							'from' : 'menu'
						},
						method : 'POST',
						success : function(response) {

							var r = Ext.decode(response.responseText);
							if (!r.success) {
								Ext.Msg.alert("提示信息", "失败，由以下原因所致：<br/>" + (r.errors ? r.errors : "未知原因"));
							} else {
								Ext.Msg.alert("提示信息", "保存成功!");
							}
						},
						failure : function(Optional) {

							Ext.Msg.alert("提示信息", "连接服务器失败!");
						},
						scope : this
					});
				},
				scope : this
			}]
		});
		this.tabs = new Ext.TabPanel({
			region : 'center',
			activeTab : 0,
			items : [this.menuResourceTree, this.controlResouceTree]
		});
		config = Ext.apply({
			items : [this.tree, this.tabs]
		}, config);
		RoleCurd.superclass.constructor.call(this, config);
	},
	createForm : function() {
		var formPanel = new Ext.form.FormPanel({
			autoScroll : true,
			frame : true,
			border : false,
			bodyStyle : 'position:relative;margin:15px 0 0px 15px',
			labelAlign : 'left',
			width : 500,
			height : 150,
			defaults : {
				width : 450
			},
			items : [{
				xtype : "hidden",
				name : "id",
				id : "id"
			}, {
				xtype : 'textfield',
				fieldLabel : '角色编码*',
				allowBlank : false,
				name : 'rolecode',
				anchor : '95%'
			}, {
				xtype : 'textfield',
				fieldLabel : '角色名称*',
				allowBlank : false,
				name : 'rolename',
				anchor : '95%'
			}, {
				xtype : 'textarea',
				fieldLabel : '备注信息',
				name : 'memo',
				anchor : '95%'
			}]
		});
		return formPanel;
	},
	onClick : function(node, event) {
		/*
		 Ext.each(this.controlResouceTree.getChecked(), function(node) {
		 node.getUI().toggleCheck(false);
		 }, this);//全部设置为不选中
		 */
		Ext.each(this.menuResourceTree.getChecked(), function(node) {
			node.getUI().toggleCheck(false);
		}, this);//全部设置为不选中
		Ext.Ajax.request({
			url : 'readRoleResourceR.action',
			params : {
				'id' : node.id || '',
				'from' : 'action'
			},
			method : 'POST',
			success : function(response) {
				//return Ext.Msg.alert("1", response.responseText.length);	
				var r = Ext.decode(response.responseText);
				if (!r.success) {
					Ext.Msg.alert("提示信息", "失败，由以下原因所致：<br/>" + (r.errors ? r.errors.join("\n") : "未知原因"));
				} else {
					if (r.rowCount > 0) {//设置为选中
						Ext.each(r.data, function(n) {
							/*
							try{
								//Ext.Msg.alert("2", "2!");		
								this.controlResouceTree.getNodeById(n.id).getUI().toggleCheck(true);
							}catch (e){
								try{
									//Ext.Msg.alert("3", "3!");	
									var node = this.menuResourceTree.getNodeById(n.id);
									if(node.isLeaf()){
										node.getUI().toggleCheck(true);		
									}
																			
								}catch(e){}
							}
							 */
							try {
								//Ext.Msg.alert("3", "3!");	
								var node = this.menuResourceTree.getNodeById(n.id);
								if (node.isLeaf()) {
									node.getUI().toggleCheck(true);
								}

							} catch (e) {
							}
						}, this);
					}
					return true;
					//Ext.Msg.alert("提示信息", "成功!");
				}
			},
			failure : function(Optional) {
				Ext.Msg.alert("提示信息", "连接服务器失败!");
				return true;
			},
			scope : this
		});
		return true;
	},
	removeData : function() {
		var record = this.tree.getSelectionModel().getSelectedNode();
		if (!record) {
			Ext.Msg.alert("提示", "请先选择要删除的记录!");
			return;
		}
		var m = Ext.MessageBox.confirm("删除提示", "是否真的要删除数据？", function(ret) {
			var ids = '';
			Ext.each(record, function(node) {
				ids += node.id + ",";
			}, this);
			if (ids.indexOf(",") > 0) {
				ids = ids.substring(0, ids.length - 1);
			}
			if (ret == "yes") {
				Ext.Ajax.request({
					url : this.baseUrl + '?cmd=remove',
					params : {
						'ids' : ids
					},
					method : 'POST',
					success : function(response) {
						var r = Ext.decode(response.responseText);
						if (!r.success) {
							Ext.Msg.alert("提示信息", "数据删除失败，由以下原因所致：<br/>" + (r.errors ? r.errors : "未知原因"));
						} else {
							Ext.Msg.alert("提示信息", "成功删除数据!", function() {
								this.refresh();
							}, this);
						}
					},
					scope : this
				});
			}
		}, this);
	},
	edit : function() {
		var record = this.tree.getSelectionModel().getSelectedNode();
		if (!record) {
			Ext.Msg.alert("提示", "请先选择要编辑的行!");
			return;
		}
		this.showWin();
		this.fp.form.loadRecord(new Ext.data.Record(record.attributes, record.id));
	},
	save : function() {
		if (this.fp.form.isValid()) {
			var id = this.fp.form.findField("id").getValue();
			var formData = this.fp.form.getValues();
			Ext.Ajax.request({
				url : this.baseUrl,
				params : {
					'jsondata' : Ext.encode(formData),
					'cmd' : (id ? "update" : "create"),
					'from' : 'action'
				},
				method : 'POST',
				success : function(response) {
					Ext.getBody().unmask();
					var r = Ext.decode(response.responseText);
					if (!r.success) {
						Ext.Msg.alert("提示信息", "失败，由以下原因所致：<br/>" + (r.errors ? r.errors : "未知原因"));
					} else {
						Ext.Msg.alert("提示信息", "保存成功!");
						this.closeWin();
						this.refresh();
					}
				},
				failure : function(Optional) {
					Ext.getBody().unmask();
					Ext.Msg.alert("提示信息", "连接服务器失败!");
					this.closeWin();
				},
				scope : this
			});

		}
	},
	refresh : function() {
		this.tree.root.reload();
		this.tree.root.expand(true);
	}
});